|
|
|
|
|
|
|
The scope of a variable sets which parts of your application code can access it. When you declare a variable within a procedure, only the code in that procedure can access or modify the data stored in that variable. This variable is said to have a scope that is local to that procedure. However, you might need to use a variable with a wider scope, such as one whose data is available to all the procedures within one module or to all the procedures in the entire application. Visual Basic enables you to specify the scope of any variable when you declare it. Depending on how a variable is declared, it is scoped as either a local or global variable: |
|
|
|
|
|
|
|
|
Local (also called private)The variable is accessible only to the code within the procedure in which it was declared. |
|
|
|
|
|
|
|
|
Global (also called public)The variable can be used by any procedure in the module in which it was declared. |
|
|
|
|
|
|
|
|
As you begin to add more modules to your project, you might find that the private variables defined within the procedures are no longer enough for your applications needs. You might need to access a variable from one module in another module. To do this, you would need to declare the variable as a public variable. |
|
|
|
|
|
|
|
|
Note Public variables can be declared only in the Declarations section of a module. They can never be declared inside a procedure. |
|
|
|
|
|
|
|
|
|
Besides the Public statement, you can also declare variables using the Private and Dim statements. The Private statement will declare a variable that can be accessed only in the module or procedure in which it was declared. Both the Dim and Private statements declare variables essentially the same way. |
|
|
|
|
|
|
|
|
Tip When writing code for your application, you should use the Private statement instead of the Dim statement to ensure that the scope of the variable is what you intended. |
|
|
|
|
|
|
|
|
|
|
Note Note that even the procedures with which you work have a scope. Generally, they are private to the module in which they are located, and only other procedures in that module can access each other. However, if you declare a procedure as Public, it will be available anywhere in the application. |
|
|
|
|
|
|
|